package com.funny.test.scan.importregistrar;

import com.funny.test.scan.FunnyScan;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author fanxiao  2021/11/22
 * @since 1.0.0
 */
public class FunnyScannerImportRegistrar implements ImportBeanDefinitionRegistrar {

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
										BeanDefinitionRegistry registry) {

		AnnotationAttributes funnyScanAttributes = AnnotationAttributes.fromMap(
				importingClassMetadata.getAnnotationAttributes(FunnyScan.class.getName()));
		if (funnyScanAttributes != null) {
			registerBeanDefinitions(importingClassMetadata, funnyScanAttributes, registry,
					generateBaseBeanName(importingClassMetadata, 0));
		}
	}

	private void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
										 AnnotationAttributes funnyScanAttributes,
										 BeanDefinitionRegistry registry,
										 String beanName) {

		BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(FunnyScannerConfigurer.class);
		Class<?> markerInterface = funnyScanAttributes.getClass("markerInterface");
		if (!Class.class.equals(markerInterface)) {
			builder.addPropertyValue("markerInterface", markerInterface);
		}
		registry.registerBeanDefinition(beanName,builder.getBeanDefinition());
	}


	private static String generateBaseBeanName(AnnotationMetadata importingClassMetadata, int index) {
		return importingClassMetadata.getClassName() + "#" + FunnyScannerImportRegistrar.class.getSimpleName() + "#" + index;
	}
}
